package com.sxbbc.seller.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.exceptions.ThrowPageException;
import com.sxbbc.common.basics.files.RestUploadFileInfo;
import com.sxbbc.common.basics.files.UploadUtils;
import com.sxbbc.common.basics.rest.RestFactory;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.regular.RpxUtils;
import com.sxbbc.common.basics.utils.statics.DynamicSettingUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.dto.jz.ProductEditVo;
import com.sxbbc.common.core.dto.jz.PropertiesVo;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.*;
import com.sxbbc.common.core.service.*;
import com.sxbbc.common.core.service.system.solr.SolrproductService;
import com.sxbbc.common.core.service.system.solr.entity.SolrProductDto;
import com.sxbbc.common.core.utils.BasePage;
import com.sxbbc.common.core.utils.FileUtils;
import com.sxbbc.common.core.utils.MultipartFileToFile;
import com.sxbbc.seller.common.BProductMapping;
import com.sxbbc.seller.util.BusinessSession;
import com.sxbbc.seller.util.SystemLog;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 商家 产品 控制层
 *
 * @author leehao
 * @date 2019-05-27 21:45
 */
@SuppressWarnings("all")
@Controller
public class BProductController {

    @Autowired
    private IProcMainService procMainService;
    @Autowired
    private ProcClassifyMainService classifyMainService;
    @Autowired
    private ProcClassifyShopService classifyShopService;
    @Autowired
    private IProcBrandInfoService brandInfoService;
    @Autowired
    private IProcInterestService procInterestService;
    @Autowired
    private IProSkuDetailService proSkuDetailService;
    @Autowired
    private BBusinessService bBusinessService;
    @Autowired
    private IProcDescribeService procDescribeService;
    @Autowired
    private IIndustryDetailService industryDetailService;
    @Autowired
    private IBExpConfigService bExpConfigService;
    @Autowired
    private IAddressService addressService;
    @Autowired
    private ICustomerLevelInfoService customerLevelInfoService;
    @Autowired
    private IProGroupConfigService proGroupConfigService;
    @Autowired
    private IWWarehouseService warehouseService;
    @Autowired
    private IWWarehouseDetailService warehouseDetailService;
    @Autowired
    private SolrproductService solrProductService;

    /**
     * 商品列表
     *
     * @param request  获取bid
     * @param page     分页条件
     * @param procMain 查询条件
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = BProductMapping.SHOW_PRODUCT_LIST)
    public ModelAndView showBProductList(HttpServletRequest request,
                                         BasePage<ProcMain> page, ProcMain procMain) {
        Integer bid = BusinessSession.getBid(request);
        BBusiness bBusiness = bBusinessService.getById(bid);
        procMain.setBid(bid);
        IPage<ProcMain> pageInfo = procMainService.queryProductList(page, procMain);
        //平台分类、主分类
        ProcThirdClassifyMain thirdClassifyMain = new ProcThirdClassifyMain();
        thirdClassifyMain.setLevel(StaticUtils.FIRST_CLASSIFY);
        List<?> firstList = classifyMainService.queryClassifyListByPlat(thirdClassifyMain);
        //店铺分类
        List<?> businessFirstList = classifyMainService.queryBusinessFirstClassifyList(bid);
        //是否需要商家分类
        ModelAndView view = new ModelAndView(BProductMapping.SHOW_PRODUCT_LIST);
        CalcuUtils calUtil = CalcuUtils.getInstance();
        //商品类型
        List<ProductTypeEnums> procTypeList = new ArrayList<>();
        if (calUtil.isEquals(bBusiness.getBType(), BusinessTypeEnums.OWN_BUSINESS.getId())) {
            procTypeList = ProductTypeEnums.queryValidList(BusinessTypeEnums.OWN_BUSINESS.getId());
        } else if (calUtil.isEquals(bBusiness.getBType(), BusinessTypeEnums.SETTLED.getId())) {
            procTypeList = ProductTypeEnums.queryValidList(BusinessTypeEnums.SETTLED.getId());
        }
        view.addObject("pageInfo", pageInfo);
        view.addObject("firstList", firstList);
        view.addObject("businessFirstList", businessFirstList);
        view.addObject("procTypeList", procTypeList);
        view.addObject("bType", bBusiness.getBType());
        view.addObject("procMain", procMain);
        view.addObject("needApply", DynamicSettingUtils.BUSINESS_PRODUCT_NEED_APPLY);
        return view;
    }

    /**
     * 新增商品页面
     *
     * @param request 获取bid
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = BProductMapping.SHOW_ADD_PRODUCT)
    public ModelAndView showAddBProduct(HttpServletRequest request) {
        CalcuUtils calUtil = CalcuUtils.getInstance();
        Integer bid = BusinessSession.getBid(request);
        BBusiness bBusiness = bBusinessService.getById(bid);
        //商品类型
        List<ProductTypeEnums> procTypeList = new ArrayList<>();
        if (calUtil.isEquals(bBusiness.getBType(), BusinessTypeEnums.OWN_BUSINESS.getId())) {
            procTypeList = ProductTypeEnums.queryValidList(BusinessTypeEnums.OWN_BUSINESS.getId());
        } else if (calUtil.isEquals(bBusiness.getBType(), BusinessTypeEnums.SETTLED.getId())) {
            procTypeList = ProductTypeEnums.queryValidList(BusinessTypeEnums.SETTLED.getId());
        }
        //平台分类、主分类
        ProcThirdClassifyMain thirdClassifyMain = new ProcThirdClassifyMain();
        thirdClassifyMain.setLevel(StaticUtils.FIRST_CLASSIFY);
        List<?> firstList = classifyMainService.queryClassifyListByPlat(thirdClassifyMain);
        //商家分类
        List<ProcFirstClassifyShop> businessFirstList = classifyMainService.queryBusinessFirstClassifyList(bid);
        //品牌
        QueryWrapper<ProcBrandInfo> brandWr = new QueryWrapper<>();
        brandWr.eq("status", StaticUtils.STATUS_YES);
        //店铺权益
        QueryWrapper<ProcInterest> interWr = new QueryWrapper<>();
        interWr.eq("type", StaticUtils.PRODUCT_INTEREST_PLATFORM).
                eq("status", StaticUtils.STATUS_YES);
        List<ProcInterest> interList = procInterestService.list(interWr);
        //商品标签
        List<ProcLabelEnums> labelList = ProcLabelEnums.queryList();
        //计价方式
        List<ValuationTypeEnums> valuationList = ValuationTypeEnums.queryList();
        //运费模板
        QueryWrapper<BExpConfig> expWrapper = new QueryWrapper<>();
        expWrapper.eq("bid", bid).eq("status", StaticUtils.STATUS_YES);
        List<BExpConfig> expList = bExpConfigService.list(expWrapper);
        //地址
        Address address = new Address();
        address.setPid(StaticUtils.ADDRESS_COUNTRY);
        List<Address> addressList = addressService.queryAddressByParentId(address);
        ModelAndView view = new ModelAndView(BProductMapping.SHOW_ADD_PRODUCT);
        view.addObject("procTypeList", procTypeList);
        view.addObject("firstList", firstList);
        view.addObject("businessFirstList", businessFirstList);
        view.addObject("interList", interList);
        view.addObject("labelList", labelList);
        view.addObject("valuationList", valuationList);
        view.addObject("businessCode", bBusiness.getBusinessCode());
        view.addObject("onOff", bBusiness.getOnOff());
        view.addObject("expList", expList);
        view.addObject("addressList", addressList);
        view.addObject("needProperties", DynamicSettingUtils.PRODUCT_PROPERTIES_NEED);
        view.addObject("groupControl", DynamicSettingUtils.GROUP_PRODUCT_NEED_DATETIME);
        return view;
    }

    /**
     * 编辑商品页面
     *
     * @param request 获取bid
     * @param proId   商品ID
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = BProductMapping.SHOW_EDIT_PRODUCT)
    public ModelAndView showEditBProduct(HttpServletRequest request, Integer proId) {
        CalcuUtils calUtil = CalcuUtils.getInstance();
        Integer bid = BusinessSession.getBid(request);
        BBusiness bBusiness = bBusinessService.getById(bid);
        ProcMain procMain = procMainService.getById(proId);
        ProGroupConfig proGroupConfig = new ProGroupConfig();
//        if (calUtil.isEquals(procMain.getProType(),ProductTypeEnums.GROUPS.getId())) {
//            proGroupConfig = proGroupConfigService.selectGroupProduct(procMain.getProCode());
//        }
        //商品类型
        List<ProductTypeEnums> procTypeList = new ArrayList<>();
        if (calUtil.isEquals(bBusiness.getBType(), BusinessTypeEnums.OWN_BUSINESS.getId())) {
            procTypeList = ProductTypeEnums.queryValidList(BusinessTypeEnums.OWN_BUSINESS.getId());
        } else if (calUtil.isEquals(bBusiness.getBType(), BusinessTypeEnums.SETTLED.getId())) {
            procTypeList = ProductTypeEnums.queryValidList(BusinessTypeEnums.SETTLED.getId());
        }
        //平台一二三级分类
        ProcThirdClassifyMain thirdClassifyMain = new ProcThirdClassifyMain();
        thirdClassifyMain.setLevel(StaticUtils.FIRST_CLASSIFY);
        List<?> firstList = classifyMainService.queryClassifyListByPlat(thirdClassifyMain);
        List<?> secondList = new ArrayList<>();
        List<?> thirdList = new ArrayList<>();
        if (procMain.getMainClassifyFirstId() != null) {
            //一级不为空查询二级
            thirdClassifyMain.setLevel(StaticUtils.SECOND_CLASSIFY);
            thirdClassifyMain.setFirstId(procMain.getMainClassifyFirstId());
            secondList = classifyMainService.queryClassifyListByPlat(thirdClassifyMain);
        }
        if (procMain.getMainClassifyFirstId() != null && procMain.getMainClassifySecondId() != null) {
            //一二级不为空查询三级
            thirdClassifyMain.setLevel(StaticUtils.THIRD_CLASSIFY);
            thirdClassifyMain.setFirstId(procMain.getMainClassifyFirstId());
            thirdClassifyMain.setSecondId(procMain.getMainClassifySecondId());
            thirdList = classifyMainService.queryClassifyListByPlat(thirdClassifyMain);
        }
        //商家分类
        List<ProcFirstClassifyShop> businessFirstList = classifyMainService.queryBusinessFirstClassifyList(bid);
        //商品标签
        List<ProcLabelEnums> labelList = ProcLabelEnums.queryList();
        //计价方式
        List<ValuationTypeEnums> valuationList = ValuationTypeEnums.queryList();
        //店铺权益
        QueryWrapper<ProcInterest> interWr = new QueryWrapper<>();
        interWr.eq("type", StaticUtils.PRODUCT_INTEREST_PLATFORM).
                eq("status", StaticUtils.STATUS_YES);
        String[] inters = {};
        if (StringUtils.isNotBlank(procMain.getInterest())) {
            inters = procMain.getInterest().split(",");
        }
        List<ProcInterest> interList = procInterestService.list(interWr);
        for (ProcInterest procInterest : interList) {
            for (String i : inters) {
                if (CalcuUtils.getInstance().isEquals(procInterest.getId(), Integer.parseInt(i))) {
                    procInterest.setCheckFlag("checked");
                }
            }
        }
        //商品属性数据
        List<PropertiesVo> propertiesList = procDescribeService.getProcPropertiesList(procMain.getProCode());
        //sku数据
        List<PropertiesVo> skuList = procDescribeService.getProcSkuList(procMain.getProCode());
        //sku详情
        List<ProSkuDetail> skuDetailList = proSkuDetailService.querySkuListByProCode(procMain.getProCode());
        //运费模板
        QueryWrapper<BExpConfig> expWrapper = new QueryWrapper<>();
        expWrapper.eq("bid", bid).eq("status", StaticUtils.STATUS_YES);
        List<BExpConfig> expList = bExpConfigService.list(expWrapper);
        //商品详情描述
        ProcDescribe describe = procDescribeService.selectByProCode(procMain.getProCode());
        //地址
        Address address = new Address();
        address.setPid(StaticUtils.ADDRESS_COUNTRY);
        List<Address> addressList = addressService.queryAddressByParentId(address);
        List<Address> cityList = new ArrayList<>();
        if (procMain.getProduceCity() != null) {
            address.setPid(procMain.getProducePro());
            cityList = addressService.queryAddressByParentId(address);
        }
        //会员等级
        List<CustomerLevelInfo> levelList = customerLevelInfoService.list();
        levelList.forEach(x -> x.setCheckFlag("disabled"));
        ModelAndView view = new ModelAndView(BProductMapping.SHOW_EDIT_PRODUCT);
        view.addObject("proc", procMain);
        view.addObject("businessCode", bBusiness.getBusinessCode());
        view.addObject("onOff", bBusiness.getOnOff());
        view.addObject("procTypeList", procTypeList);
        view.addObject("firstList", firstList);
        view.addObject("secondList", secondList);
        view.addObject("thirdList", thirdList);
        view.addObject("businessFirstList", businessFirstList);
        view.addObject("labelList", labelList);
        view.addObject("valuationList", valuationList);
        view.addObject("interList", interList);
        view.addObject("propertiesList", propertiesList);
        view.addObject("skuList", skuList);
        view.addObject("skuDetailList", skuDetailList);
        view.addObject("expList", expList);
        view.addObject("describe", describe);
        view.addObject("addressList", addressList);
        view.addObject("cityList", cityList);
        view.addObject("levelList", levelList);
        view.addObject("proGroupConfig", proGroupConfig);
        view.addObject("needProperties", DynamicSettingUtils.PRODUCT_PROPERTIES_NEED);
        view.addObject("groupControl", DynamicSettingUtils.GROUP_PRODUCT_NEED_DATETIME);
        return view;
    }

    /**
     * 新增商品
     *
     * @param request  获取bid
     * @param procMain
     * @param product
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = BProductMapping.ADD_PRODUCT)
    @ResponseBody
    @SystemLog(methods = "新增商品", module = "商品管理")
    public RestResponse addBProduct(HttpServletRequest request,
                                    ProcMain procMain,
                                    ProductEditVo product,
                                    @RequestParam(required = false) MultipartFile cover) {
        Integer bid = BusinessSession.getBid(request);
        if (bid == null) {
            return GetRest.getFail("商家登录异常，请重新登录");
        }
        BBusiness bBusiness = bBusinessService.getById(bid);
//        if (CalcuUtils.getInstance().isEquals(bBusiness.getOnOff(), BusinessScopeEnums.OFFLINE.getId())) {
//            return GetRest.getFail("线下店铺无法新增线上商品！");
//        }
        //商品编码重复性验证
        if (!this.handleCheckProCode(request, procMain.getProCode())) {
            return GetRest.getFail("该商品编码已存在");
        }
        //参数共用方法校验
        RestResponse checkResult = checkProductParams(procMain, product);
        if (!checkResult.isStatus()) {
            return checkResult;
        }
        //处理主图
        if (StringUtils.isNotBlank(procMain.getProImgs())) {
            String[] img = procMain.getProImgs().split(",");
            procMain.setProUrl(img[0]);
        }
        if (cover != null) {
            /*RestUploadFileInfo result = UploadUtils.getInstance().uploadFileQN(cover);
            if (result.isStatus()) {
                procMain.setCoverUrl(result.getData());
            } else if (!result.isStatus() && cover != null) {
                return GetRest.getFail("图片上传失败: " + result.getDesc());
            }*/

            try {
                File fe= MultipartFileToFile.multipartFileToFile(cover);
                String url = FileUtils.up(fe);
                procMain.setCoverUrl(url);
            }catch (Exception e){
                return GetRest.getFail("图片上传失败，请重试");
            }

        }
        //商品编码处理，加上商家编码 统一大写
        procMain.setProCode(bBusiness.getBusinessCode() + procMain.getProCode().toUpperCase());
        //审核状态
        procMain.setExamineStatus(StaticUtils.STATUS_YES);
        //商品bid
        procMain.setBid(bBusiness.getId());
        //该版本商品保存后是否需要审核
        if (DynamicSettingUtils.PRODUCT_NEED_PLAT_APPLY) {
            procMain.setExamineStatus(ProductStatusEnums.NO_CHECK.getId());
        } else {
            procMain.setExamineStatus(ProductStatusEnums.HAS_CHECK.getId());
        }
        return procMainService.addBusinessProduct(procMain, product);
    }

    /**
     * 处理商品编辑
     *
     * @param procMain
     * @param productEditVo
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = BProductMapping.EDIT_PRODUCT)
    @ResponseBody
    public RestResponse editProduct(HttpServletRequest request,
                                    ProcMain procMain,
                                    ProductEditVo productEditVo,
                                    @RequestParam(required = false) MultipartFile cover) {
        Integer bid = BusinessSession.getBid(request);
        if (bid == null) {
            return GetRest.getFail("商家登录异常，请重新登录！");
        }
        BBusiness bBusiness = bBusinessService.getById(bid);
        ProcMain proc = procMainService.selectOneByProCode(procMain.getProCode());
        if (proc == null) {
            return GetRest.getFail("该商品不存在！");
        }
        if (!CalcuUtils.getInstance().isEquals(procMain.getProType(), proc.getProType()) &&
                !CalcuUtils.getInstance().isEquals(procMain.getProType(), ProductTypeEnums.NORMAL.getId()) &&
                StringUtils.isNotBlank(proc.getActivitySign())) {
            return GetRest.getFail("该商品已参加 " + proc.getActivitySign() + " 活动，不可变更为其它类型商品！");
        }
        //参数共用方法校验
        RestResponse checkResult = checkProductParams(procMain, productEditVo);
        if (!checkResult.isStatus()) {
            return checkResult;
        }
        //处理封面图
        if (cover != null) {
            /*RestUploadFileInfo result = UploadUtils.getInstance().uploadFileQN(cover);
            if (result.isStatus()) {
                procMain.setCoverUrl(result.getData());
            } else if (!result.isStatus() && cover != null) {
                return GetRest.getFail("图片上传失败: " + result.getDesc());
            }*/
            try {
                File fe= MultipartFileToFile.multipartFileToFile(cover);
                String url = FileUtils.up(fe);
                procMain.setCoverUrl(url);
            }catch (Exception e){
                return GetRest.getFail("图片上传失败，请重试");
            }
        }
        //处理主图
        if (StringUtils.isNotBlank(procMain.getProImgs())) {
            String[] img = procMain.getProImgs().split(",");
            procMain.setProUrl(img[0]);
        }
        //商品bid
        procMain.setBid(bBusiness.getId());
        //该版本商品保存后是否需要平台审核
        if (DynamicSettingUtils.PRODUCT_NEED_PLAT_APPLY) {
            procMain.setStatus(ProductStatusEnums.UNSHELVES.getId());
            procMain.setExamineStatus(ProductStatusEnums.NO_CHECK.getId());
        } else {
            procMain.setExamineStatus(ProductStatusEnums.HAS_CHECK.getId());
        }
        return procMainService.editBusinessProduct(procMain, productEditVo);
    }

    /**
     * 校验商品编码唯一性
     *
     * @param request 获取商家编码
     * @param proCode 商品编码
     * @return boolean
     * @author leehao
     */
    @RequestMapping(value = BProductMapping.HANDLE_CHECK_PRO_CODE)
    @ResponseBody
    public boolean handleCheckProCode(HttpServletRequest request, String proCode) {
        if (StringUtils.isBlank(proCode)) {
            return false;
        }
        if (!RpxUtils.getInstance().validProCode(proCode)) {
            return false;
        }
        //商家编码前缀
        String businessCode = BusinessSession.getBusinessCode(request);
        ProcMain procMain = procMainService.selectOneByProCode(businessCode + proCode.toUpperCase());
        return procMain == null;
    }

    /**
     * sku编码重复性验证
     *
     * @param request 获取bid
     * @param skuCode sku编码 json字符串
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = BProductMapping.HANDLE_CHECK_SKU_CODE)
    @ResponseBody
    public RestResponse handleCheckSkuCode(HttpServletRequest request, String skuCode, String proCode) {
        Integer bid = BusinessSession.getBid(request);
        if (bid == null) {
            return GetRest.getFail("商家登录异常，请重新登录");
        }
        if (skuCode == null) {
            return GetRest.getFail("请输入SKU编码");
        }
        //处理sku编码 逗号分隔
        JSONArray skuArray = JSONArray.parseArray(skuCode);
        List<String> codeList = new ArrayList<>();
        Set<String> repeatSet = new HashSet<String>();
        RpxUtils rxpUtil = RpxUtils.getInstance();
        for (Object s : skuArray) {
            if (!rxpUtil.validProCode(s.toString().toUpperCase())) {
                return GetRest.getFail("SKU编码格式有误");
            }
            if (s.toString().toUpperCase().length() > 10) {
                return GetRest.getFail("SKU编码长度过长(最长10位)");
            }
            codeList.add(s.toString().toUpperCase());
            repeatSet.add(s.toString().toUpperCase());
        }
        if (codeList.size() != repeatSet.size()) {
            return GetRest.getFail("页面输入的SKU编码有重复");
        }
        List<String> list = proSkuDetailService.queryRepeatSkuCode(bid, codeList, proCode);
        //list为空则sku编码可用，否则返回重复的sku编码
        if (CollectionUtils.isEmpty(list) && list.size() < 1) {
            return GetRest.getSuccess("SKU编码可用！");
        } else {
            return GetRest.getFail("", list);
        }
    }

    /**
     * 处理商品状态
     *
     * @param procMain 商品信息
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = BProductMapping.HANDLE_PRODUCT_STATUS)
    @ResponseBody
    public RestResponse handleProductStatus(ProcMain procMain) {
        if (procMain.getStatus() == null) {
            return GetRest.getFail("商品状态异常");
        }
        return procMainService.handleProductStatus(procMain);
    }

    /**
     * 批量处理商品状态
     *
     * @param type  类型
     *              1 上架
     *              2 下架
     *              3 审核
     * @param idArr 选中ID
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = BProductMapping.HANDLE_PRODUCT_STATUS_BATCH)
    @ResponseBody
    public RestResponse handleProductStatusBatch(Integer type, String idArr) {
        if (type == null) {
            return GetRest.getFail("请选择要操作的类型！");
        }
        if (StringUtils.isBlank(idArr)) {
            return GetRest.getFail("没有数据被选中！");
        } else {
            idArr = idArr.replace("\"", "");
        }
        String[] ids = idArr.split(",");
        return procMainService.handleProductStatusBatch(type, ids);
    }

    /**
     * 设置商品的价格、库存页面
     *
     * @param proCode 商品编码
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = BProductMapping.SHOW_EDIT_PRICE_STOCK)
    public ModelAndView showEditProductPrice(String proCode) {
        if (StringUtils.isBlank(proCode)) {
            throw new ThrowPageException("该商品编码信息不存在！");
        }
        ProcMain procMain = procMainService.selectOneByProCode(proCode);
        List<ProSkuDetail> skuList = proSkuDetailService.querySkuListByProCode(proCode);
        for (ProSkuDetail proSkuDetail : skuList) {
            proSkuDetail.setProType(procMain.getProType());
        }
        ModelAndView view = new ModelAndView(BProductMapping.SHOW_EDIT_PRICE_STOCK);
        view.addObject("skuList", skuList);
        view.addObject("proType", procMain.getProType());
        return view;
    }

    /**
     * 商品列表页设置价格库存
     *
     * @param skuDetail
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = BProductMapping.EDIT_PRICE_STOCK)
    @ResponseBody
    public RestResponse editProductPrice(ProSkuDetail skuDetail) {
        CalcuUtils calUtil = CalcuUtils.getInstance();
        boolean update = false;
        ProSkuDetail sku = proSkuDetailService.getById(skuDetail.getId());
        ProcMain procMain = procMainService.selectOneByProCode(sku.getProCode());
        //当设置库存时，要对库存进行更新
        if (skuDetail.getQty() != null) {
            //原库存
            Integer originalQty = sku.getQty();
            //新库存
            Integer newQty = skuDetail.getQty();
            procMain.setQty(procMain.getQty() - originalQty + newQty);
        }
//        else if(skuDetail.getGroupPrice() != null){
//            if (!calUtil.isEquals(procMain.getProType(),ProductTypeEnums.GROUPS.getId())) {
//                return GetRest.getFail("非团购商品无法设置团购价！");
//            }
//        }
        update = proSkuDetailService.updateById(skuDetail);
        if (!update) {
            throw new ThrowJsonException("更新商品详情失败");
        }
        //修改第一组规格的价格时 更新商品商品主表价格与solr缓存
        SolrProductDto solrProductDto = solrProductService.selectById(procMain.getProCode());
        if (skuDetail.getIndex() != null && calUtil.isEquals(skuDetail.getIndex(), 1)) {
            procMain.setPrice(skuDetail.getPrice());
            solrProductDto.setProprice(String.valueOf(skuDetail.getPrice()));

        }
        update = procMainService.updateById(procMain);
        if (!update) {
            throw new ThrowJsonException("更新商品信息失败");
        }
        RestResponse solrResult = solrProductService.addProduct(solrProductDto);
        if (!solrResult.isStatus()) {
            throw new ThrowJsonException("更新商品到缓存失败");
        }
        return GetRest.getSuccess("更新成功");
    }

    /**
     * 添加商品到仓储管理页面
     *
     * @param proCode 商品编码
     * @author leehao
     */
    @RequestMapping(value = BProductMapping.SHOW_EDIT_PRODUCT_WAREHOUSE)
    public ModelAndView showEditProductWarehouse(String proCode) {
        //已添加到仓库的商品list
        List<WWarehouseDetail> list = new ArrayList<>();
        if (StringUtils.isNotBlank(proCode)) {
            QueryWrapper<WWarehouseDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("pro_code", proCode);
            list = warehouseDetailService.list(wrapper);
            for (WWarehouseDetail d : list) {
                d.setWarehouseName(warehouseService.getById(d.getWid()).getName());
                d.setSpecName(proSkuDetailService.getById(d.getSkuId()).getSpecName());
            }
        }
        //仓库list
        QueryWrapper<WWarehouse> wrapper = new QueryWrapper<>();
        wrapper.eq("status", StaticUtils.STATUS_YES);
        List<WWarehouse> warehouseList = warehouseService.list(wrapper);
        //商品详情
        List<ProSkuDetail> skuList = proSkuDetailService.querySkuListByProCode(proCode);
        ModelAndView view = new ModelAndView(BProductMapping.SHOW_EDIT_PRODUCT_WAREHOUSE);
        view.addObject("proList", list);
        view.addObject("warehouseList", warehouseList);
        view.addObject("proCode", proCode);
        view.addObject("skuList", skuList);
        return view;
    }

    /**
     * 保存商品到仓储管理或更新数据
     *
     * @param detail
     * @author leehao
     */
    @RequestMapping(value = BProductMapping.EDIT_PRODUCT_WAREHOUSE)
    @ResponseBody
    public RestResponse editProductWarehouse(WWarehouseDetail detail) {
        if (detail.getId() == null && detail.getWid() == null) {
            return GetRest.getFail("请选择仓库");
        }
        if (detail.getId() == null && detail.getSkuId() == null) {
            return GetRest.getFail("请选择规格");
        }
        if (detail.getId() == null && detail.getQty() == null) {
            return GetRest.getFail("请输入数量");
        }
        //查询是否添加过
        QueryWrapper<WWarehouseDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("pro_code", detail.getProCode()).eq("sku_id", detail.getSkuId()).eq("wid", detail.getWid());
        int count = warehouseDetailService.count(wrapper);
        if (count > 0) {
            return GetRest.getFail("该规格已添加，请直接在表格中更新哦～");
        }
        boolean save = false;
        if (detail.getId() == null) {
            save = warehouseDetailService.save(detail);
        } else {
            save = warehouseDetailService.updateById(detail);
        }
        if (!save) {
            throw new ThrowJsonException("保存商品仓库信息失败");
        }
        return GetRest.getSuccess("保存成功");
    }

    /**
     * 图片上传
     *
     * @param file 图片文件
     * @return 图片url
     * @author leehao
     */
    @RequestMapping(value = BProductMapping.UPLOAD_IMAGES)
    @ResponseBody
    public RestResponse uploadImages(@RequestParam(required = false) MultipartFile file) {
        /*RestUploadFileInfo result = UploadUtils.getInstance().uploadFileQN(file);
        String url = "";
        if (result.isStatus()) {
            url = result.getData();
        } else if (!result.isStatus() && file != null) {
            return GetRest.getFail("上传图片失败");
        }
        return GetRest.getSuccess("上传成功", url);*/
        try {
            File fe= MultipartFileToFile.multipartFileToFile(file);
            String path= FileUtils.up(fe);
            return GetRest.getSuccess("上传成功", path);
        }catch (Exception e){
            return GetRest.getFail("上传图片失败");
        }
    }

    /**
     * 商品权益列表
     *
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = BProductMapping.SHOW_PRODUCT_INTEREST)
    public ModelAndView showProductInterestList(HttpServletRequest request) {
        Integer bid = BusinessSession.getBid(request);
        QueryWrapper<ProcInterest> wrapper = new QueryWrapper<>();
        wrapper.eq("type", StaticUtils.PRODUCT_INTEREST_PLATFORM).
                eq("status", StaticUtils.STATUS_YES);
        List<ProcInterest> list = procInterestService.list(wrapper);
        ModelAndView view = new ModelAndView(BProductMapping.SHOW_PRODUCT_INTEREST);
        view.addObject("list", list);
        return view;
    }

    @RequestMapping(value = BProductMapping.SHOW_EDIT_PRODUCT_INTEREST)
    public ModelAndView showEditProductInterest(Integer id) {
        ProcInterest interest = procInterestService.getById(id);
        ModelAndView view = new ModelAndView(BProductMapping.SHOW_EDIT_PRODUCT_INTEREST);
        view.addObject("interest", interest);
        return view;
    }

    @RequestMapping(value = BProductMapping.EDIT_PRODUCT_INTEREST)
    @ResponseBody
    @SystemLog(methods = "新增/编辑商家权益", module = "商品管理")
    public RestResponse editProductInterest(HttpServletRequest request, ProcInterest interest) {
        //获取商家登录对象，拿到bid
        Integer bid = BusinessSession.getBid(request);
        if (bid == null) {
            return GetRest.getFail("登录异常，请重新登录");
        }
        if (StringUtils.isBlank(interest.getName())) {
            return GetRest.getFail("请输入权益名称");
        }
        if (StringUtils.isBlank(interest.getContent())) {
            return GetRest.getFail("请输入权益内容");
        }
        //type直接在表单中设置了为2，即为商家的权益
        //设置targetId
        interest.setTargetid(bid);
        boolean save = procInterestService.saveOrUpdate(interest);
        if (!save) {
            throw new ThrowJsonException("商家保存权益失败");
        }
        return GetRest.getSuccess("保存成功");
    }

    @RequestMapping(value = BProductMapping.DELETE_PRODUCT_INTEREST)
    @ResponseBody
    @SystemLog(methods = "商家删除商品权益", module = "商品管理")
    public boolean deleteProductInterest(Integer id) {
        boolean del = procInterestService.removeById(id);
        if (!del) {
            throw new ThrowJsonException("商家删除商品权益失败");
        }
        return del;
    }

    /**
     * 通过主行业id查询子行业
     *
     * @param pid 主行业id
     * @return
     */
    @RequestMapping(value = BProductMapping.QUERY_INDUSTRY_DETAIL)
    @ResponseBody
    public RestResponse queryIndustryDetail(Integer pid) {
        QueryWrapper<IndustryDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("status", StaticUtils.STATUS_YES).eq("ind_id", pid);
        return GetRest.getSuccess("", industryDetailService.list(wrapper));
    }

    /**
     * 商品新增、编辑时公用校验
     *
     * @param procMain 商品主对象
     * @param product  商品辅助对象
     * @author leehao
     */
    private RestResponse checkProductParams(ProcMain procMain, ProductEditVo product) {
        if (StringUtils.isBlank(procMain.getProName())) {
            return GetRest.getFail("请输入商品名称！");
        }
        if (StringUtils.isBlank(procMain.getProCode())) {
            return GetRest.getFail("请输入商品编码！");
        }
        if (procMain.getProCode().length() > 22) {
            return GetRest.getFail("商品编码填写过长！");
        }
        if (procMain.getProType() == null) {
            return GetRest.getFail("请选择商品类型！");
        }
        if (DynamicSettingUtils.SAVE_PRODUCT_NEED_PLATFORM_CLASSIFY) {
            if (procMain.getMainClassifyFirstId() == null) {
                return GetRest.getFail("请选择平台分类一级分类");
            }
            if (procMain.getMainClassifySecondId() == null) {
                return GetRest.getFail("请选择平台分类二级分类");
            }
            if (procMain.getMainClassifyFirstId() == null) {
                return GetRest.getFail("请选择平台分类三级分类");
            }
        }
        if (procMain.getProducePro() == null || procMain.getProduceCity() == null) {
            return GetRest.getFail("请选择商品产地！");
        }
        if (procMain.getExpId() == null) {
            return GetRest.getFail("请选择运费模板！");
        }
        if (StringUtils.isBlank(procMain.getProDesc())) {
            return GetRest.getFail("请输入商品描述！");
        }
        if (procMain.getValuationType() == null) {
            return GetRest.getFail("请选择计价方式！");
        }
        if (StringUtils.isBlank(procMain.getProUnit())) {
            return GetRest.getFail("请输入商品单位名称！");
        }
        if (procMain.getProUnit().length() > 10) {
            return GetRest.getFail("商品单位请勿超过10个字符！");
        }
        if (procMain.getSort() != null && (procMain.getSort() > 100 || procMain.getSort() < 1)) {
            return GetRest.getFail("商品排序请输入1~100以内的数");
        }
        CalcuUtils cal = CalcuUtils.getInstance();
        //重量计价
        if (cal.isEquals(procMain.getValuationType(), ValuationTypeEnums.WEIGHT.getId())) {
            if (procMain.getWeightUnit() == null) {
                return GetRest.getFail("请输入重量单位！");
            }
        }
        if (procMain.getSort() != null) {
            if (procMain.getSort() > 100) {
                return GetRest.getFail("商品排序填写数值过大");
            }
        }
        //虚拟已售
        if (procMain.getIsInvented() != null) {
            if (procMain.getInventedNum() == null) {
                return GetRest.getFail("请输入虚拟已售数量！");
            }
        }
        if (StringUtils.isNotBlank(procMain.getProDesc()) && procMain.getProDesc().length() > 255) {
            return GetRest.getFail("商品描述内容过长，支持最大字符为255！");
        }
        //商品图片
        if (StringUtils.isBlank(procMain.getProImgs())) {
            return GetRest.getFail("请上传商品图片！");
        }
        if (DynamicSettingUtils.PRODUCT_PROPERTIES_NEED) {
            //商品属性部分
            if (product.getProperties() == null) {
                return GetRest.getFail("请输入商品属性！");
            }
            if (product.getPropertiesVal() == null) {
                return GetRest.getFail("请输入商品属性值！");
            }
        }
        if (StringUtils.isBlank(product.getSkuArr())) {
            return GetRest.getFail("请填写商品SKU编码！");
        }
        if (StringUtils.isBlank(product.getPcDetail())) {
            return GetRest.getFail("请填写商品详情信息！");
        }
        return GetRest.getSuccess("校验成功");
    }

    /**
     * 查询商品详情列表
     *
     * @param proCode 产品编号
     * @return
     * @author Wahyee
     */
    @RequestMapping(value = BProductMapping.QUERY_PRODUCT_DETAIL)
    @ResponseBody
    public com.sxbbc.common.basics.rest.RestResponse queryProSkuDetail(String proCode) {
        QueryWrapper<ProSkuDetail> queryWrapper = new QueryWrapper<ProSkuDetail>();
        queryWrapper.eq("pro_code", proCode);
        return RestFactory.success(proSkuDetailService.querySkuListByProCode(proCode));
    }

    /**
     * 商品规格图片上传页
     *
     * @param id SKU信息ID
     * @return
     * @author Wahyee
     */
    @RequestMapping(value = BProductMapping.SHOW_PRODUCT_DETAIL_IMG)
    public ModelAndView showProductDetailImg(Integer id) {
        ModelAndView view = new ModelAndView(BProductMapping.SHOW_PRODUCT_DETAIL_IMG);
        view.addObject("detail", proSkuDetailService.getById(id));
        return view;
    }

    /**
     * 修改商品详情图片
     *
     * @param id     商品详情ID
     * @param imgUrl 图片地址
     * @return
     * @author Wahyee
     */
    @RequestMapping(value = BProductMapping.UPDATE_PRODUCT_DETAIL_IMG)
    @ResponseBody
    public com.sxbbc.common.basics.rest.RestResponse updateProductDetailImg(Integer id, String imgUrl) {
        ProSkuDetail entity = new ProSkuDetail();
        entity.setId(id);
        entity.setImgUrl(imgUrl);
        return RestFactory.center(proSkuDetailService.updateById(entity), "保存成功", "保存失败");
    }
}
